package demo.IOInputOutput;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.PrintWriter;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/12-08-12-14:07
 * @Description：demo.IOInputOutput   文件管道流
 */
public class IOFilePipe {
    public static void main(String[] args) {
        //声明创建流
        PipedReader reader = new PipedReader();
        PipedWriter writer = new PipedWriter();

        //建立管道之间的连接
        try {
            reader.connect(writer);
            new FileWriterThread(writer).start();
            Thread.sleep(10);
            new FileReaderThread(reader).start();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class FileWriterThread extends Thread{
    private PipedWriter writer = null;

    public FileWriterThread(PipedWriter writer) {
        this.writer = writer;
    }

    @Override
    public void run() {
        //char[] origin  = "中国!".toCharArray();
        char[] origin  = "hello world!".toCharArray();
        byte[] b = new byte[1024];
        try {
            writer.write(origin);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer != null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
class FileReaderThread extends Thread{
    private PipedReader reader;
    private PrintWriter print;

    public FileReaderThread(PipedReader reader) {
        this.reader = reader;
    }

    @Override
    public void run() {
        int len = -1;
        char[] b = new char[1024];
        try {
//            if (((len = reader.read(b)) != -1)) {
//                print = new PrintWriter(System.out);
//                print.write(b,0,len);
//                print.flush();
//            }
            while((len = reader.read()) != -1){
                System.out.write(len);
                System.out.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        }
}
